//
//  HomeViewController.m
//  Fireball
//
//  Created by 俞渊华 on 2017/12/2.
//  Copyright © 2017年 俞渊华. All rights reserved.
//

#import "HomeViewController.h"
#import "NavgationSearchView.h"
#import "MenuTool.h"
#import "XLChannelControl.h"

#import "JMColumnMenu.h"

#import "HMSegmentedControl.h"

#import "HomeBaseViewController.h"
#import "HomeVideoViewController.h"
#import "FBSearchViewController.h"
#import "PageContollerCell.h"
#import "JYJSliderMenuTool.h"

#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "WBPopMenuView.h"
#import "SpotCreateViewController.h"
#import "CKHttpCommunicate.h"
#import "RouteViewController.h"
#import "ChangeShiftViewController.h"
#import "SpotTaskViewController.h"
#import "AuditViewController.h"
#import "pictureData.h"
#import "FMUploadModel.h"
#import <AFNetworking.h>

static NSString *reuseID = @"itemCell";

@interface HomeViewController ()
<
NavgationSearchViewDelegate,
JMColumnMenuDelegate,
UICollectionViewDelegate,
UICollectionViewDataSource
>


/** menuView */
@property (nonatomic, strong) JMColumnMenu *menu;
@property(nonatomic, strong)UIButton *menuButton;
@property (nonatomic ,retain)UICollectionView * collectionView;
@property (nonatomic ,retain) HMSegmentedControl *header;

@property(nonatomic, strong)NSMutableArray *aticleArray;
@property(nonatomic, strong)NSMutableArray *selectedArray;
@property(nonatomic, copy)NSArray *showMenua;
//下载hud
@property (nonatomic,strong) MBProgressHUD  *HUD;
@property (nonatomic,strong)UIButton* spotBtn;
@property (nonatomic,strong)NSTimer* timer;
//超时
@property (nonatomic,assign) int overTime;
//网路状态
@property (nonatomic,assign) BOOL network;

//离线图片
@property(nonatomic,strong)NSMutableArray* selectImgs;
@property(nonatomic,strong)NSMutableArray* models;
@end

@implementation HomeViewController

static HomeViewController *hvc = nil;

+ (instancetype)share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hvc = [[self alloc] init];
    });
    return hvc;
}
-(void)setNavigationItem{
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    UIColor *color1= XMColor(255, 70, 93);
//    UIColor *color2 = XMColor(251, 108, 42);
//    gradientLayer.colors = @[(__bridge id)color1.CGColor, (__bridge id)color2.CGColor];
//    gradientLayer.locations = @[@0.5, @1.0];
//    gradientLayer.startPoint = CGPointMake(0, 0);
//    gradientLayer.endPoint = CGPointMake(1.0, 0);
//    gradientLayer.bounds = CGRectMake(0, 0, SCREEN_WIDTH*2, 64+26);
//    [self.navigationController.navigationBar.layer addSublayer:gradientLayer];
    
    UIImage *leftImage = [[UIImage imageNamed:@"menu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemClick)];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"home_message"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //两个按钮的父类view
    
    UIView *rightButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 50)];
    //refresh按钮
    UIButton *refreshBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    
    [rightButtonView addSubview:refreshBtn];
    
    [refreshBtn setImage:[UIImage imageNamed:@"ic_autorenew"] forState:UIControlStateNormal];
    
    [refreshBtn addTarget:self action:@selector(postPhoto) forControlEvents:UIControlEventTouchUpInside];
    
    //临时任务添加按钮
    
    UIButton *historyBtn = [[UIButton alloc] initWithFrame:CGRectMake(50, 0, 50, 50)];
    
    [rightButtonView addSubview:historyBtn];
    
    [historyBtn setImage:[UIImage imageNamed:@"ic_add"] forState:UIControlStateNormal];
    
    [historyBtn addTarget:self action:@selector(historyBtnEvent) forControlEvents:UIControlEventTouchUpInside];
    _spotBtn=historyBtn;
    _spotBtn.hidden=YES;
    //提交按钮
    
    UIButton *mainAndSearchBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 50, 50)];
    
    [rightButtonView addSubview:mainAndSearchBtn];
    
    [mainAndSearchBtn setImage:[UIImage imageNamed:@"overflow_icon"] forState:UIControlStateNormal];
    
    [mainAndSearchBtn addTarget:self action:@selector(mainAndSearchBtnEvent) forControlEvents:UIControlEventTouchUpInside];
    
    //把右侧的两个按钮添加到rightBarButtonItem
    
    UIBarButtonItem *rightCunstomButtonView = [[UIBarButtonItem alloc] initWithCustomView:rightButtonView];
    
    self.navigationItem.rightBarButtonItem = rightCunstomButtonView;


    NavgationSearchView * searchView = [[NavgationSearchView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    searchView.delegate = self;
//    self.navigationItem.titleView = searchView;
    self.title=@"任务箱";
    // Title view label
    CGRect labelFrame = CGRectMake(0.0, 0.0, SCREEN_WIDTH, 36.0);
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    label.font = [UIFont boldSystemFontOfSize:18];
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentLeft;
    label.textColor = [UIColor whiteColor];
//    label.shadowColor = [UIColor blackColor];
//    label.shadowOffset = CGSizeMake(0.0, -1.0);
    label.lineBreakMode = UILineBreakModeMiddleTruncation;
    label.text=@"任务箱";
    self.navigationItem.titleView = label;
//    [self.navigationItem.titleView setBackgroundColor:[UIColor redColor]];

//    [label mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.navigationItem.titleView.mas_left).offset(0);
//        make.centerY.equalTo(self.navigationItem.titleView.mas_centerY);
//    }];
//    self.navigationController.navigationBar.translucent = YES;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationItem];
    //要显示的标题
    self.showMenua = [MenuTool userSelectedMenu];
    [self createNav];
    [self createCollectionView];
    _succCount=0;
    _nosuccCount=0;
    _totalCount=0;
//    [self.menuButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.right.mas_equalTo(self.view);
//        make.size.mas_equalTo(CGSizeMake(44, 44));
//    }];
//    [self.header mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.right.mas_equalTo(self.view);
//        make.right.mas_equalTo(self.menuButton.mas_left);
//        make.height.mas_equalTo(@44);
//    }];
//    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.bottom.right.mas_equalTo(self.view);
//        make.top.mas_equalTo(self.header.mas_bottom);
//    }];
    self.overTime=0;
    
    self.models=[NSMutableArray array];
    self.selectImgs=[NSMutableArray array];
    //网路状态
    [MySingleton sharedMySingleton].network=YES;
    [self reachbality];
}
-(void)refreshBtnEvent
{
    if (![RouteViewController share].orderCopy) {
        [RouteViewController share].orderCopy=[WorkOrderModel findAll];
    }
    if (![ChangeShiftViewController share].orderCopy) {
        [ChangeShiftViewController share].orderCopy=[WorkOrderModel findAll];
    }
    if (![SpotTaskViewController share].orderCopy){
        [SpotTaskViewController share].orderCopy=[WorkOrderModel findAll];
    }
    if (![AuditViewController share].orderCopy){
        [AuditViewController share].orderCopy=[WorkOrderModel findAll];
    }
    if (!self.timer) {

        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
    }
    [MySingleton sharedMySingleton].succCount=0;
    [MySingleton sharedMySingleton].nosuccCount=0;
    [MySingleton sharedMySingleton].totalCount=0;

    [[RouteViewController share] gcdpost];
    [[ChangeShiftViewController share] gcdpost];
    [[SpotTaskViewController share] gcdpost];
    [[AuditViewController share] gcdpost];
    
}
-(void)updateTimer:(NSTimer*)timer
{
    int a=[MySingleton sharedMySingleton].succCount+[MySingleton sharedMySingleton].nosuccCount;
    int b=[MySingleton sharedMySingleton].totalCount;
    NSLog(@"tttttt%d--%d",a,b);
    if (a==b) {
        [self.timer invalidate];
        self.timer=nil;
        if ([_delegate respondsToSelector:@selector(syncSuccess)]) {
            [_delegate syncSuccess];
        }
    }
    self.overTime++;
    if (self.overTime>5) {
        [self.timer invalidate];
        self.timer=nil;
        if ([_delegate respondsToSelector:@selector(syncSuccess)]) {
            [_delegate syncSuccess];
        }
    }
}
-(void)reachbality
{
    // 网络监控
    AFNetworkReachabilityManager *networkReachbilityManager = [AFNetworkReachabilityManager sharedManager];
    
    [networkReachbilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
                
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"GZQ1-未知网络");
                [MySingleton sharedMySingleton].network=YES;
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"GZQ1-断网");
                [MySingleton sharedMySingleton].network=NO;
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"GZQ1-蜂窝数据");
                [MySingleton sharedMySingleton].network=YES;
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"GZQ1-WiFi网络");
                [MySingleton sharedMySingleton].network=YES;
                break;
                
            default:
                break;
        }
    }];
    
    // 开启监控
    [networkReachbilityManager startMonitoring];
}
-(void)postPhoto
{
    if (![MySingleton sharedMySingleton].network) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"请检查网络状态" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    [self.models removeAllObjects];
    self.selectImgs=[pictureData findAll];
    NSMutableArray* sopTemp=[NSMutableArray new];
    for (pictureData* model in self.selectImgs) {
        if (!model.picurl) {
            [sopTemp addObject:model];
        }
    }
    [self.selectImgs removeAllObjects];
    self.selectImgs=sopTemp;

    //开辟一个多线程 执行图片上传工作
    dispatch_queue_t queue = dispatch_queue_create("upimgs", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        // 耗时操作放在这里
        
        __weak typeof(self) weakself = self;
        __block int finishNum = 0;
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/digiops/upload/uploadPhoto",kBaseUrl]];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        //设置请求实体
        NSMutableData *body = [NSMutableData data];
        
        for (int i=0; i<self.selectImgs.count; i++) {
            NSData *imageData;
            NSString *imageFormat;
            imageFormat = @"Content-Type: image/jpeg \r\n";
            pictureData* pc=(pictureData*)[self.selectImgs objectAtIndex:i];
            imageData = pc.picraw;
            
            [body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
            
            NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.png\"\r\n",@"photo",@"photo"];
            [body appendData:[self getDataWithString:disposition ]];
            [body appendData:[self getDataWithString:imageFormat]];
            [body appendData:[self getDataWithString:@"\r\n"]];
            [body appendData:imageData];
            [body appendData:[self getDataWithString:@"\r\n"]];
            
            //普通参数
            [body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
        }
        
        //上传参数需要key： （相应参数，在这里是_myModel.personID）
        for (int i=0; i<self.selectImgs.count; i++) {
            
            NSString *dispositions = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",@"key"];
            [body appendData:[self getDataWithString:dispositions ]];
            [body appendData:[self getDataWithString:@"\r\n"]];
            [body appendData:[self getDataWithString:@"photo"]];
            [body appendData:[self getDataWithString:@"\r\n"]];
            
            
            //参数结束
            [body appendData:[self getDataWithString:@"--BOUNDARY--\r\n"]];
        }
        //***********//
        //            FMUploadModel *model = [FMUploadModel new];
        //            model.dataArray = body;
        //            model.imgUrl = @"";
        //            model.picuuid=pc.picuuid;
        //            [self.models addObject:model];
        /*******其实是一张一张传的，传数组是调用这个方法**********/
        
        request.HTTPBody = body;
        //设置请求体长度
        NSInteger length = [body length];
        [request setValue:[NSString stringWithFormat:@"%ld",length] forHTTPHeaderField:@"Content-Length"];
        //设置 POST请求文件上传
        [request setValue:@"multipart/form-data; boundary=BOUNDARY" forHTTPHeaderField:@"Content-Type"];
        NSURLSession *session = [NSURLSession sharedSession];
        dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            //        self.HUD.progress = 1.0f;
            //        _HUD.labelText = [NSString stringWithFormat:@"%2.f%%",1.00f*100];
            if (data) {
                finishNum ++ ;
                
                NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSDictionary *dict = (NSDictionary *)object;
                NSLog(@"=====%@",[dict objectForKey:@"success"]);
                for (NSDictionary* content in dict[@"content"]) {
                    
                    FMUploadModel* model=[FMUploadModel mj_objectWithKeyValues:content];
                    model.dataArray=nil;
                    [self.models addObject:model];
                    //                    [model saveOrUpdateAsync:^(BOOL isSuccess) {
                    //
                    //                    }];
                }
                for (int i=0; i<self.selectImgs.count; i++) {
                    
                    pictureData* pc=(pictureData*)[self.selectImgs objectAtIndex:i];
                    FMUploadModel* modelurl=[self.models objectAtIndex:i];
                    pc.picurl=modelurl.path;
                    [pc saveOrUpdate];//先上传图片，结束后再上传工单
//                    [pc saveOrUpdateAsync:^(BOOL isSuccess) {
//
//                    }];
                }
                NSLog(@"");
                dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];

                [self refreshBtnEvent];
                                });

                
            }
            else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"图片上传失败，请重新同步" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alert show];
                });
            }
        }];
        //开始任务
        [dataTask resume];
        
    });
}

-(NSData *)getDataWithString:(NSString *)string{
    
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    return data;
    
}
-(void)historyBtnEvent
{
    SpotCreateViewController* detailVC = [[SpotCreateViewController alloc]init];
    //     detailVC.model = self.aticleArray[indexPath.row];
    [self.rt_navigationController pushViewController:detailVC animated:YES];
}
-(void)mainAndSearchBtnEvent
{
    [self rightBarButtonItemClick];
}
-(void)createNav{
    
    self.header = [[HMSegmentedControl alloc] init];
    self.header.frame = CGRectMake(0, 0, self.view.bounds.size.width, 44);
    self.header.backgroundColor = DGColor;
    self.header.segmentEdgeInset = UIEdgeInsetsMake(0, 12, 0, 12);
    
    //    self.header.selectedTitleTextAttributes = @{NSForegroundColorAttributeName : [UIColor xm_MainColor],NSFontAttributeName:[UIFont xm_medium:16.f]};
//    self.header.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor xm_colorFromRGB:0xB1BCCB],NSFontAttributeName:[UIFont xm_font:16.f]};
    self.header.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor lightGrayColor],NSFontAttributeName:[UIFont xm_font:16.f]};
    self.header.selectedTitleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName:[UIFont xm_font:16.f]};
    self.header.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;//设定线条的位置
//    self.header.selectionIndicatorColor = [UIColor xm_MainColor];//线条的颜色
    self.header.selectionIndicatorColor=[UIColor whiteColor];
    self.header.verticalDividerEnabled = YES;
    self.header.verticalDividerColor = [UIColor whiteColor];
    self.header.verticalDividerWidth = 2.0f;
    
    self.header.selectionIndicatorHeight = 3.f;
    self.header.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;//线充满整个长度
    [self.header addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.header];
    [self setSegmentedTitleText];
    
    self.menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.menuButton.frame = CGRectMake(self.view.width - 44, 0, 44, 44);
    [self.menuButton setImage:[UIImage imageNamed:@"home_filter"] forState:UIControlStateNormal];
    [self.menuButton addTarget:self action:@selector(menuButtonClick:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:self.menuButton];
    
}

-(void)menuButtonClick:(UIButton *)sender{
    NSArray *arr1 = [MenuTool userSelectedMenu];
    NSArray *arr2 = [MenuTool userUnselectedMenu];
    JMColumnMenu *menuVC = [JMColumnMenu columnMenuWithTagsArrM:arr1 OtherArrM:arr2 Type:JMColumnMenuTypeTouTiao Delegate:self];
    [self presentViewController:menuVC animated:YES completion:nil];
}

-(void)setSegmentedTitleText{
    NSMutableArray * array = [NSMutableArray array];
    for (AticleMenu * menu in self.showMenua) {
        [array addObject:menu.Text];
    }
    self.header.sectionTitles = array;
    [self setPowerTitleText];
}

-(void)changeSegmentedTitleText{
    NSMutableArray * array = [NSMutableArray array];
    for (AticleMenu * menu in self.showMenua) {
        [array addObject:@"123"];
    }
    self.header.sectionTitles = array;
}
-(void)setPowerTitleText{
    NSMutableArray * array = [NSMutableArray array];
    for (AticleMenu * menu in self.showMenua) {
        if ([menu.Text hasPrefix:@"任务"])
            [array addObject:menu.Text];

    }
    self.header.sectionTitles = array;
}
-(void)createCollectionView{
    UICollectionViewFlowLayout *layout =[[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-kNav_Height - 44);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView =[[UICollectionView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT-kNav_Height - 44) collectionViewLayout:layout];
    self.collectionView.delegate =self;
    self.collectionView.dataSource = self;
    self.collectionView.bounces = YES;
    self.collectionView.pagingEnabled = YES;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[PageContollerCell class] forCellWithReuseIdentifier:reuseID];
}

- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl{
    if (segmentedControl.selectedSegmentIndex==0)
        [MySingleton sharedMySingleton].finished=NO;
    else
        [MySingleton sharedMySingleton].finished=YES;
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:segmentedControl.selectedSegmentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    if ([MySingleton sharedMySingleton].finished) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSDate* password = [defaults objectForKey:@"finishedList"];
        if (!password) {
        [[HomeBaseViewController share] postFinishUI];
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setObject:@"1" forKey:@"finishedList"];
            [userDefault synchronize];
        }
        
    }
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.showMenua.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PageContollerCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
    AticleMenu * menu = self.showMenua[indexPath.row];
    if (menu.menuId == 206) {//视屏
        HomeVideoViewController * videoVC = [[HomeVideoViewController alloc] init];
        [cell.contentView addSubview:videoVC.view];
        videoVC.menu = self.showMenua[indexPath.row];
        [self addChildViewController:videoVC];
        return cell;
        
    }else{
        HomeBaseViewController * baseVC = [[HomeBaseViewController alloc] init];
        [cell.contentView addSubview:baseVC.view];
        baseVC.menu = self.showMenua[indexPath.row];
        [self addChildViewController:baseVC];
        _delegate=baseVC;
        baseVC.block = ^(int a, int b) {
            BOOL menu=YES;
//            for (NSDictionary* d in [UserInfo share].role.menuRoleDTOs) {
//                if ([[d objectForKey:@"menuName"] isEqualToString:@"已完成工单"]) {
//                    menu=NO;
//                }
//                NSLog(@"");
//            }
            if ([[UserInfo share].role.powerType isEqualToString:@"1"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                [self setPowerTitleText];
                    self.collectionView.scrollEnabled=NO;
                });
            }
            else
                _spotBtn.hidden=NO;

//            if (menu) {
//                [self setPowerTitleText];
//            }
            NSMutableArray * array = [NSMutableArray array];
            for (AticleMenu * menu in self.showMenua) {
                if ([menu.Text hasPrefix:@"任务"])
                    menu.Text=[NSString stringWithFormat:@"任务(%d)",a];

                [array addObject:menu.Text];
            }
            self.header.sectionTitles = array;
        };
        baseVC.blockFinish = ^(int a, int b) {
            NSMutableArray * array = [NSMutableArray array];
            for (AticleMenu * menu in self.showMenua) {
                if ([menu.Text hasPrefix:@"  已完成任务"])
                    menu.Text=[NSString stringWithFormat:@"  已完成任务(%d)",a];
                
                [array addObject:menu.Text];
            }
            self.header.sectionTitles = array;
        };
        return cell;
    }

}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    CGFloat offsetx =scrollView.contentOffset.x;
    NSInteger index = offsetx/SCREEN_WIDTH;
    [self.header setSelectedSegmentIndex:index animated:YES];
}

- (void)columnMenuTagsArr:(NSMutableArray *)tagsArr OtherArr:(NSMutableArray *)otherArr {
    ///先清除存储的数据，不然顺序会有问题
    [AticleMenu clear];
    for (AticleMenu * menu in tagsArr) {
        [menu saveOrUpdate];
    }
    for (AticleMenu * menu in otherArr) {
        [menu saveOrUpdate];
    }
    self.showMenua = tagsArr;
    [self setSegmentedTitleText];
    [self.collectionView reloadData];

}


-(void)leftBarButtonItemClick{
    // 展示个人中心
    [JYJSliderMenuTool showWithRootViewController:self];
}
-(void)rightBarButtonItemClick{
    NSMutableArray *obj = [NSMutableArray array];
    
    for (NSInteger i = 0; i < [self titles].count; i++) {
        
        WBPopMenuModel * info = [WBPopMenuModel new];
        //        info.image = [self images][i];
        info.title = [self titles][i];
        [obj addObject:info];
    }
    
    [[WBPopMenuSingleton shareManager]showPopMenuSelecteWithFrame:150
                                                             item:obj
                                                           action:^(NSInteger index) {
                                                               NSLog(@"index:%ld",(long)index);
                                                               //执行代理方法
                                                               if ([_delegate respondsToSelector:@selector(homeDidSelectedAtIndex:)]) {
                                                                   [_delegate homeDidSelectedAtIndex:index];
                                                               }
                                                           }];
}
- (NSArray *) titles {
    return @[@"排序",
             @"优先级",
             @"开始时间",
             @"状态"];
}

- (NSArray *) images {
    return @[@"right_menu_QR@3x",
             @"right_menu_addFri@3x",
             @"right_menu_multichat@3x",
             @"right_menu_sendFile@3x",
             @"right_menu_facetoface@3x",
             @"right_menu_payMoney@3x"];
}
-(void)homePageNavigationSearchClick{
    FBSearchViewController * searchVC = [[FBSearchViewController alloc] init];

    RTRootNavigationController * nav = [[RTRootNavigationController alloc] initWithRootViewController:searchVC];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark -- init MBProgressHUD
- (void)hudTipWillShow:(BOOL)willShow{
    if (willShow) {
        [self resignFirstResponder];
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        if (!_HUD) {
            _HUD = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
            _HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
            _HUD.progress = 0;
            _HUD.labelText = @"0%";
            _HUD.removeFromSuperViewOnHide = YES;
        }else{
            _HUD.progress = 0;
            _HUD.labelText = @"0%";
            [keyWindow addSubview:_HUD];
            [_HUD show:YES];
        }
    }else{
        [_HUD hide:YES];
    }
}


@end
